package im.starchat.chat.activity.profile;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.pingplusplus.android.PaymentActivity;

import org.json.JSONObject;
import org.json.JSONTokener;

import butterknife.ButterKnife;
import butterknife.InjectView;
import im.starchat.chat.R;
import im.starchat.chat.XLApplication;
import im.starchat.chat.activity.BaseActivity;
import im.starchat.chat.adapter.MyDiamondAdapter;
import im.starchat.chat.impl.IProductBuyCallback;
import im.starchat.chat.rest.model.AccountBean;
import im.starchat.chat.rest.model.ProductBean;
import im.starchat.chat.rest.model.api.ConfigResponse;
import im.starchat.chat.rest.model.api.NullResponse;
import im.starchat.chat.utils.PreferencesStorageUtil;
import im.starchat.chat.utils.Util;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;


/**
 * 提现,我的收益
 */
public class MyDiamondActivity extends BaseActivity implements View.OnClickListener{

    @InjectView(R.id.mydiamond_back)
    ImageView mBackBtn;
    @InjectView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @InjectView(R.id.diamond_last)
    TextView mDiamondLast;

    private GridLayoutManager mLayoutManager;

    private MyDiamondAdapter mMyDiamondAdapter;

    private static final int REQUEST_CODE_PAYMENT = 1;

    /**
     * 银联支付渠道
     */
    private static final String CHANNEL_UPACP = "upacp";
    /**
     * 微信支付渠道
     */
    private static final String CHANNEL_WECHAT = "wx";
    /**
     * 支付支付渠道
     */
    private static final String CHANNEL_ALIPAY = "alipay";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mydiamond);
        ButterKnife.inject(this);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new GridLayoutManager(this, 2);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mMyDiamondAdapter = new MyDiamondAdapter(this, new IProductBuyCallback() {
            @Override
            public void onBuy(ProductBean productBean) {
                pay(productBean.getId() + "", "wx", productBean.getAmount(), productBean.getPrice());
            }
        });

        mDiamondLast.setText(PreferencesStorageUtil.getDiamondCount(MyDiamondActivity.this) + "");
        mRecyclerView.setAdapter(mMyDiamondAdapter);
        getDiamondList();

        mBackBtn.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mydiamond_back:
                finish();
                break;
        }
    }

    @Override
    protected void onResume() {

        getAccountInfo();
        super.onResume();
    }

    private AccountBean mAccountBean;
    private void getAccountInfo(){
        showProgressDialog();
        XLApplication.getInstance().getRestClient().getAccountInfo(new Callback<AccountBean>() {
            @Override
            public void success(AccountBean accountBean, Response response) {
                dismissProgressDialog();
                if (accountBean != null) {
                    mAccountBean = accountBean;
                    mDiamondLast.setText(accountBean.getAmount() + "");
                    PreferencesStorageUtil.setDiamondCount(MyDiamondActivity.this, accountBean.getAmount());
//                    if (accountBean.getProducts() != null) {
//                        mMyDiamondAdapter.refreshProductList(configResponse.getProducts());
//                    }
                }
            }

            @Override
            public void failure(RetrofitError error) {
                dismissProgressDialog();
            }
        });
    }

    private void getDiamondList(){
        showProgressDialog();
        XLApplication.getInstance().getRestClient().getConfig(new Callback<ConfigResponse>() {
            @Override
            public void success(ConfigResponse configResponse, Response response) {
                if (configResponse != null) {
                    if (configResponse.getProducts() != null) {
                        mMyDiamondAdapter.refreshProductList(configResponse.getProducts());
                    }
                }
                getAccountInfo();


            }

            @Override
            public void failure(RetrofitError error) {
                dismissProgressDialog();
            }
        });
    }


    private void pay(String product_id, String channel, int amount, float price){
        XLApplication.getInstance().getRestClient().pay(product_id, channel, amount, price, new Callback<NullResponse>() {
            @Override
            public void success(NullResponse nullResponse, Response response) {
                Intent intent = new Intent(MyDiamondActivity.this, PaymentActivity.class);
                try{
                    JSONTokener jsonParser = new JSONTokener(Util.inputStream2String(response.getBody().in()));
                    JSONObject data = (JSONObject) jsonParser.nextValue();
                    //TODO 支付
                    if(data != null){
                        JSONObject ChargeData = data.getJSONObject("data");
                        intent.putExtra(PaymentActivity.EXTRA_CHARGE, ChargeData.toString());
                        System.out.println("pay_data--->" + ChargeData.toString());
                        startActivityForResult(intent, REQUEST_CODE_PAYMENT);
                    }

                }catch (Exception e){
                    e.printStackTrace();
                    toast("支付失败", Toast.LENGTH_SHORT);
                }

            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    /**
     * onActivityResult 获得支付结果，如果支付成功，服务器会收到ping++ 服务器发送的异步通知。
     * 最终支付成功根据异步通知为准
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        //支付页面返回处理
        if (requestCode == REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                String result = data.getExtras().getString("pay_result");
                /* 处理返回值
                 * "success" - payment succeed
                 * "fail"    - payment failed
                 * "cancel"  - user canceld
                 * "invalid" - payment plugin not installed
                 */
                String errorMsg = data.getExtras().getString("error_msg"); // 错误信息
                String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息
                System.out.println("result--->" + result);

                if(result.equals("success")){
                    toast("支付成功", Toast.LENGTH_SHORT);
                }else if(result.equals("fail")){
                    toast("支付失败", Toast.LENGTH_SHORT);
                }else if(result.equals("cancel")){
                    toast("支付取消", Toast.LENGTH_SHORT);
                }else if(result.equals("invalid")){
                    toast("未安装微信", Toast.LENGTH_SHORT);
                }


//                toast(errorMsg + extraMsg, Toast.LENGTH_SHORT);
//                toast("支付失败", Toast.LENGTH_SHORT);
            }
        }
    }


//    public void pay( String product_id, String channel, int amount, float price, Callback<NullResponse> callback){
//        xlService.pay(product_id, channel, amount, price, callback);
//    }
//
//
//    private void getDiamondList(){
//            XLApplication.getInstance().getRestClient().getConfig(new Callback<ConfigResponse>() {
//                @Override
//                public void success(ConfigResponse configResponse, Response response) {
//                    if(configResponse != null){
//                        if(configResponse.getProducts()!= null){
//                            mMyDiamondAdapter.refreshProductList(configResponse.getProducts());
//                        }
//                    }
//                }
//
//                @Override
//                public void failure(RetrofitError error) {
//
//                }
//            });
//    }
}
